package com.camtc.camcenter.controller.login;

import com.camtc.camcenter.bean.dto.LoginDto;
import com.camtc.camcenter.config.jwt.JwtAuthenticationToken;
import com.camtc.camcenter.custom.CamHttpResult;
import com.camtc.camcenter.custom.ResultStatusCode;
import com.camtc.camcenter.redis.RedisKeyRule;
import com.camtc.camcenter.util.JwtTokenUtils;
import com.camtc.camcenter.util.RedisUtils;
import com.camtc.camcenter.util.SecurityUtils;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.camtc.camcenter.custom.ResultStatusCode.INVALID_TOKEN;

/**
 * 登录Controller
 *
 * @author
 * @date
 */

@Api
@RestController
public class LoginController {

    private AuthenticationManager authenticationManager;

    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    private Producer producer;

    @Autowired
    public void setProducer(Producer producer) {
        this.producer = producer;
    }

    private RedisUtils redisUtils;

    @Autowired
    public void setRedisUtils(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }


    /**
     * JWT登录接口
     *
     * @param loginDto
     * @param request
     * @return
     */
    @PostMapping(value = "/jwt/login")
    public CamHttpResult login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        // 验证码验证
        String verifyKey = RedisKeyRule.getLoginVerifyKey(loginDto.getCode());
        if (!redisUtils.exists(verifyKey) || !StringUtils.equals(redisUtils.get(verifyKey).toString(), loginDto.getCode())) {
            return CamHttpResult.failure(ResultStatusCode.INVALID_CAPTCHA);
        }
        // 系统登录认证
        JwtAuthenticationToken token = SecurityUtils.login(request, loginDto.getUsername(), loginDto.getPassword(), authenticationManager);
        // 返回Token
        return CamHttpResult.ok(token.getToken());
    }

    /**
     * 验证token是否过期
     *
     * @return
     */
    @PostMapping(value = "/jwt/validate")
    public CamHttpResult validate(@RequestParam String token, @RequestParam String username) {
        if (JwtTokenUtils.validateToken(token, username)) {
            return CamHttpResult.ok("验证通过");
        } else {
            return CamHttpResult.failure(INVALID_TOKEN);
        }
    }

    /**
     * 登录验证码
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        String verifyCode = producer.createText();
        String verifyKey = RedisKeyRule.getLoginVerifyKey(verifyCode);
        while (redisUtils.exists(verifyKey)) {
            verifyKey = RedisKeyRule.getLoginVerifyKey(verifyCode);
        }
        redisUtils.set(verifyKey, verifyCode);
        redisUtils.expireKey(verifyKey, 60L, TimeUnit.SECONDS);
        BufferedImage image = producer.createImage(verifyCode);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        }
    }

}
